<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Grid;
use App\Models\GridImg;
use App\Models\Village;
use App\Models\Villager;
use App\Models\PrintLog;
use App\Models\SignSet;
use App\Models\ProtocolSet;
use App\Models\GridArea;
use App\Models\GridAssess;
use App\Models\GridHouse;
use App\Models\GridPrice;
use App\Models\SignSetType;
use App\Models\Agent;
use App\Models\ApprovalList;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;

// 打印
class PrintController extends Controller
{
    //搜索
    public function index(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'keywords' => 'required',
        ], [
            'keywords.required' => '请输入身份证',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $project_id=auth('admin')->user()->project_id??auth('api')->user()->project_id;

        $grid_id_arr = Villager::query()
            ->where('identity_card', $params['keywords'])
            ->where('project_id',$project_id )
            ->pluck('grid_id')
            ->toArray();

        $data = Grid::query()
            ->select('id', 'name')
            ->where('project_id', $project_id)
            ->where(function ($query) use ($grid_id_arr,$params) {
                $query->whereIn('id', $grid_id_arr)
                ->orWhere('name',$params['keywords']);
              })
            ->get()
            ->toArray();

        return showData($data);
    }

    // 列表
    public function show($id)
    {
        if (empty($id)) {
            return showError('参数错误');
        }
        // data：网格信息
        $grid = Grid::query()
            ->select('id', 'name','business_imgs')
            ->where('id', $id)
            ->with('villager:id,name,identity_card,phone,grid_id')
            ->first()
            ->toArray();
        
        if (empty($grid)) {
            return showError('获取信息失败');
        }

        // type:基本信息打印：2土地证3房产证4其他证明5签约6腾房7建房手续8营业执照10代理人
        $type=GridImg::query()->where('grid_id', $id)->pluck('type')->toArray(); 
        if($grid['business_imgs']){
            array_push($type,8);
        }
        $agent=Agent::query()->where('grid_id', $id)->first(); 
        if($agent){
            array_push($type,10);
        }

        // sign_set_type：可打印模板
        $template_id_arr= ApprovalList::query()
                ->where('grid_id',$id)
                ->where('apply_status',1)
                ->orderByDesc('id')
                ->pluck('apply_type')
                ->toArray();

        $sign_set_type = SignSetType::query()
        ->when($id, function ($query) use ($template_id_arr) {
            $query->where(function($query) use ($template_id_arr){
                $query->WhereIn('template_id',$template_id_arr)->orWhere('template_id', 0);
            });
        })
        ->orderBy('id')
        ->get()
        ->toArray();        

        $data['data']=$grid;
        $data['type']=$type;
        $data['sign_set_type']=$sign_set_type;

        return showData($data);
    }

    /**
     * 1:户口本
     * 2土地证
     * 3房产证
     * 4其他证明
     * 5签约
     * 6腾房
     * 7建房手续
     * 8营业执照
     * 9模板打印
     * 10代理人
     * 11身份证
     */
    public function edit($type, Request $request)
    {
        if (empty($type)) {
            return showError('类型不能为空!');
        }

        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'print_type' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'print_type.required' => '请输入打印类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $request->all();
        $params['type'] = $type;//1查看2打印
        $data = $this->getData($params);
        if (!$data) {
            return showError('未录入数据，无法操作');
        }
        if (isset($data['code']) && $data['code'] == 0) {
            return $data;
        }
        if ($params['print_type'] == 9) {
            $return_type = $request->input('return_type', 1);
            if($return_type==1){//返回html
                return view('print/protocol', ["data" => $data]);
            }elseif($return_type==2){//返回pdf
                return showData($data['pdf_url']);
            }else{
                return showError('返回类型格式错误');
            }
        }

        return showData($data);
       
    }

    // 获取打印数据
    public function getData($params)
    {
        $print_type = $params['print_type'];
        switch ($print_type) {
            case $print_type < 8:
                if ($print_type == 1) {
                    if (!isset($params['villager_id'])) {
                        return showError('缺少村民id参数');
                    }
                    $villager_id = $params['villager_id'];
                } else {
                    $villager_id = '';
                }
                $data = GridImg::query()
                    ->select('imgs', 'type')
                    ->where('type', $print_type)
                    ->where('grid_id', $params['grid_id'])
                    ->when($villager_id, function ($query) use ($villager_id) {
                        $query->where('villager_id', $villager_id);
                    })
                    ->first();
                if ($data) {
                    $data['imgs'] = $data['imgs'] ? $this->getImageUrl($data['imgs'], 1) : [];
                }

                $res = $data;
                break;
            case 8:
                $data = Grid::query()
                    ->select('id', 'business_imgs')
                    ->where('id', $params['grid_id'])
                    ->first();
                if ($data['business_imgs']) {
                    $data['imgs'] = $data['business_imgs'] ? $this->getImageUrl($data['business_imgs'], 1) : [];
                    $data['type'] = 8;
                } else {
                    $data = [];
                }

                $res = $data;
                break;
            case 9:
                $data=$this->getProtocolData($params);  
                if (isset($data['code']) && $data['code'] == 0) {
                    return $data;
                }
                //额外打印数据
                $print_data['supply_form'] = $data['supply_form'];
                $print_data['build_form'] = $data['build_form'];
                $print_data['auto_num'] = $data['auto_num'];
                $print_data['sign_set_type'] = $params['sign_set_type'];
                $print_data['number_header'] = $data['number_header'];

                $res = $data;
                break;
            case 10:   
                $data = Agent::query()
                        ->where('grid_id',$params['grid_id'])
                        ->first();
                if($data){
                    $data['id_obverse_img']=isset($data['id_obverse_img'])?$this->getImageUrl($data['id_obverse_img']):[];
                    $data['id_reverse_img']=isset($data['id_reverse_img'])?$this->getImageUrl($data['id_reverse_img']):[];
                } 
                
                $res = $data;
                break;
            case 11:
                if (!isset($params['villager_id'])) {
                    return showError('缺少村民id参数');
                }
                $data = Villager::query()->select('id_obverse_img', 'id_reverse_img')->where('id', $params['villager_id'])->first();
                if ($data) {
                    $imgs[] = $data['id_obverse_img'] ? $this->getImageUrl($data['id_obverse_img']) : [];
                    $imgs[] = $data['id_reverse_img'] ? $this->getImageUrl($data['id_reverse_img']) : [];
                    $data['imgs'] = $imgs;
                    $data['type'] = 7;
                }

                $res = $data;
                break;    
            default:
                return showError('打印类型错误');
        }

        // 记录打印数据
        if ($params['type'] == 2) {
            $gridInfo = Grid::query()
                ->select('id', 'project_id', 'supply_form','sign_time')
                ->where('id', $params['grid_id'])
                ->first();

            $admin_id = auth('admin')->user()->id ?? 0;
            $print_data['grid_id'] = $params['grid_id'];
            $print_data['project_id'] = $gridInfo['project_id'];
            $print_data['print_type'] = $params['print_type'];
            $print_data['content'] = $params['print_type']!=9?json_encode($data):$data['pdf_url'];
            $print_data['admin_id'] = $admin_id;
            $add = PrintLog::query()->create($print_data);
            // 记录网格是否签约
            $type = SignSetType::query()->where('id', $params['sign_set_type']??0)->value('type');
            if($params['print_type']==9&&$type==1){//签约
                $update_data['if_sign']=1;
                $update_data['sign_time']=$gridInfo['sign_time']??date('Y-m-d H:i:s');
                $update_data['sign_num']=$data['number_header']??'';
                $update = Grid::query()->where('id', $params['grid_id'])->update($update_data);
            }
        }
        return $res;
    }

}
